package dialer.client.web.controlador;

import java.io.IOException;
import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;

import dialer.ws.base.entity.vtelcom.Usuario;
import dialer.ws.common.util.FacesUtils;
import dialer.ws.security.service.AuthenticationService;

@ManagedBean(name = "login")
@SessionScoped
public class LoginController {

	protected Logger log = Logger.getLogger(getClass());
	private Usuario usuario;
	private Date fecha;
	private String error;

	public LoginController() {
		usuario = new Usuario();
		fecha = new Date();
		error = new String();
	}

	// private List<String> autorizaciones = new ArrayList<String>();
	// private List<String> opciones = new ArrayList<String>();

	@ManagedProperty("#{authenticationService}")
	private AuthenticationService authenticationService;

	public void doLogin() throws ServletException, IOException {
		log.info("### doLogin");
		// boolean success = authenticationService.login(usuario.getUsername(), usuario.getPassword());
		// if (success) {
		// FacesUtils.addInfoMessage("Bienenido", usuario.getUsername());
		// } else {
		// FacesUtils.addErrorMessage("Error", error);
		// }
		ServletRequest sr = (ServletRequest) FacesUtils.getRequest();
		RequestDispatcher dispatcher = (sr).getRequestDispatcher("/j_spring_security_check?j_username="
				+ usuario.getUsername() + "&j_password=" + usuario.getPassword());
		dispatcher.forward((ServletRequest) FacesUtils.getRequest(), (ServletResponse) FacesUtils.getResponse());
		FacesContext.getCurrentInstance().responseComplete();
	}

	public void doLogout() throws ServletException, IOException {
		log.info("### doLogout");
		authenticationService.logout();
		ServletRequest sr = (ServletRequest) FacesUtils.getRequest();
		RequestDispatcher dispatcher = (sr).getRequestDispatcher("/j_spring_security_logout");
		dispatcher.forward((ServletRequest) FacesUtils.getRequest(), (ServletResponse) FacesUtils.getResponse());
		FacesContext.getCurrentInstance().responseComplete();
	}

	public void actualizaHora() {
		fecha = new Date();
	}

	public AuthenticationService getAuthenticationService() {
		return authenticationService;
	}

	public void setAuthenticationService(AuthenticationService authenticationService) {
		this.authenticationService = authenticationService;
	}

	public Usuario getUsuario() {
		return usuario;
	}

	public void setUsuario(Usuario usuario) {
		this.usuario = usuario;
	}

	public Date getFecha() {
		return fecha;
	}

	public void setFecha(Date fecha) {
		this.fecha = fecha;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

}
